<template>
    <div class="scrollContainer" :key="currentTime" :style="{ height: `${height}px` }">
        <div class="scrollHead" v-if="showColumns" :style="{
            height: headerHeight + 'px',
        }">
            <div v-for="l in columns" :key="l.key" :style="{ width: l.width }">
                {{ l.title }}
            </div>
        </div>
        <ul class="scrollBody" ref="wrapperDom" :style="{ height: !showColumns ? `${height}px`: `${height - headerHeight}px` }"
            @mouseenter="handleEnter" @mouseleave="handleLeave" @wheel="handleWheel">
            <ul ref="childDom1">
                <li v-for="(l, i) in dataSource" :data-key="rowKey ? l[rowKey] : `list${i}`"
                    :key="rowKey ? l[rowKey] : `list${i}`" :style="{ height: `${rowHeight}px` }">
                    <div v-for="(p, c) in columns" :key="`p${c}`" :style="getStyle(p, l)" @click="(e) => {
                        e.stopPropagation()
                        onCellClick(l, p)
                        onRowClick?.(l)
                    }
                        ">
                        <span>{{ p?.render?.(i, l, l[p.key]) || l[p.key] }}</span>
                    </div>
                </li>
            </ul>
            <ul ref="childDom2"></ul>
        </ul>
    </div>
</template>

<script setup lang="ts">
import { onMounted, watch, ref, onBeforeUnmount, computed, nextTick } from 'vue'

interface ViewProps {
    height: number
    dataSource: Record<string, any>[] // 数据源
    columns: TableColumn[] // 列定义
    headerHeight?: number
    rowHeight?: number
    onRowClick?: (l: Record<string, any>) => void
    rowKey?: string
    scroll?: boolean,  // 是否开启自动滚动
    showColumns?: boolean
}

export interface TableColumn {
    key: string
    title: string
    width: string
    render?: (index: number, data: Record<string, any>, text: any) => any
    onClick?: (data: Record<string, any>) => void
}

const props = defineProps<ViewProps>()
const { height, columns, rowHeight =32, headerHeight = 36, rowKey, showColumns = false } = props

const wrapperDom = ref<any>()
const childDom1 = ref<any>()
const childDom2 = ref<any>()
const currentTime = ref(new Date().getTime())
let count = 0
let reqAnimation: number
let isScrolling = ref(true) // 用于控制是否滚动
let isWheelActive = ref(false) // 控制鼠标滚轮是否有效
let isDataRendered = ref(false) // 用于确保数据只渲染一次
const emits = defineEmits(['cellClick'])
onMounted(() => {
    nextTick(() => {
        if (props.scroll) {
            reqAnimation = window.requestAnimationFrame(taskStart)
        }
    })
})

onBeforeUnmount(() => {
    cancelScroll()
})

const dataSource = computed(() => {
    return props.dataSource
})

watch(
    () => props.dataSource,
    () => {
        currentTime.value = new Date().getTime()
    }
)

const getStyle = (p, l) => {
    let pStyle = { width: `${p.width}`, 'text-align': 'center' }
    if (l.lineColor) {
        pStyle['color'] = l.lineColor
    }
    return pStyle
}

// 初始化时间
var startTime = null,
    stepInMs = 100,
    drawCount = 0

const taskStart = (timestamp: any) => {
    var progress
    if (startTime === null) {
        startTime = timestamp
    }
    progress = timestamp - startTime!
    if (progress > stepInMs) {
        startTime = timestamp
        // 处理列表滚动逻辑
        if (childDom1.value?.clientHeight >= wrapperDom.value?.clientHeight &&
            childDom2.value?.clientHeight < 10 && !isDataRendered.value
        ) {
            childDom2.value.innerHTML = childDom1.value.innerHTML
            isDataRendered.value = true // 确保数据只渲染一次
        }
        // 当到达底部时停止滚动
        if (wrapperDom.value?.scrollTop >= childDom1.value?.scrollHeight) {
            wrapperDom.value.scrollTop = 0
            count = 0
            stopScroll()
        } else {
            count += 1
            wrapperDom.value.scrollTop = count
        }
    }

    if (isScrolling.value && !isWheelActive.value) {
        reqAnimation = window.requestAnimationFrame(taskStart)
    }
}

const handleEnter = () => {
    cancelScroll()
}

const handleLeave = () => {
    if (!isWheelActive.value) {
        reqAnimation = window.requestAnimationFrame(taskStart)
    }
}

const cancelScroll = () => {
    window.cancelAnimationFrame(reqAnimation)
    isScrolling.value = false
}

const startScroll = () => {
    isScrolling.value = true
    reqAnimation = window.requestAnimationFrame(taskStart)
}

const stopScroll = () => {
    isScrolling.value = false
    cancelScroll()
}

const onCellClick = (l: Record<string, any>, p: TableColumn) => {
    p?.onClick?.(l)
    emits('cellClick', l)
}

// 鼠标滚轮事件处理
const handleWheel = (e: WheelEvent) => {
    isWheelActive.value = true
    stopScroll()
    // 如果鼠标滚轮滚动，停止滚动
    //setTimeout(() => {
    //    isWheelActive.value = false
    //}, 200) // 停止滚动后延迟恢复自动滚动
}
</script>

<style lang="less" scoped>
.scrollContainer {
    width: 100%;

    .scrollHead {
        display: flex;
        align-items: center;
        background-color: rgba(33, 60, 93, 0.55);

        div {
            font-size: 14px;
            font-stretch: normal;
            letter-spacing: 0;
            font-family: MicrosoftYaHei, sans-serif;
            font-weight: bold;
            color: #ffffff;
            opacity: 0.47;
        }
    }

    .scrollBody {
        overflow-y: scroll;
        width: 100%;
        padding: 0;
        scrollbar-width: none;
        -ms-overflow-style: none;

        ul {
            height: auto;
            padding: 0;
            margin: 0;
        }

        ul > li {
            list-style: none;
            position: relative;
            cursor: pointer;
            display: flex;
            height: 36px;
            color: #fff;
            align-items: center;
        }

        li div {
            line-height: 32px;
            height: 32px;
            color: #fff;
            white-space: nowrap;
            /* 文本不换行 */
            overflow: hidden;
            /* 溢出部分隐藏 */
            text-overflow: ellipsis;
            /* 溢出部分用"..."代替 */
        }

        li {
            div {
                &:first-child {
                    span {
                        display: inline-block;
                        background-color: rgba(255, 255, 0, 0.533);
                        border: 1px solid rgb(0, 128, 0);
                        padding: 0 6px;
                        border-radius: 9px;
                        line-height: 1;
                    }
                }
            }
        }

        &::-webkit-scrollbar {
            display: none;
        }

        li {
            &:nth-child(2n) {
                background: rgba(40, 85, 138, .2);
                color: #fff;
            }
        }
    }
}
</style>